<template>
  <div class="filterconfig">
    <div class="content" v-for="group, mindex in groups" :key="mindex">
      <div class="clearfix content-wrap">
        <p style="width:100%;font-size:12px;">满足以下所有条件</p>
        <div class="left">
          <span style="margin:auto">且</span>
        </div>
        <div class="right">
          <div class="selectgroup" v-for="andItem, index in group.andConditions" :key="index">
            <el-select  filterable v-model="andItem.field" value-key="field" placeholder="请选择" class="filed-select" @change="changeFiled($event, mindex, index, 'andConditions')">
              <el-option
                v-for="andFileItem, index in filedConfig"
                :key="index"
                :label="andFileItem.alias || andFileItem.name"
                :value="andFileItem.field">
              </el-option>
            </el-select>
            <el-select filterable v-model="andItem.operator" @change="changeOprator(mindex, index, 'andConditions')" placeholder="请选择" class="filed-select">
              <el-option
                v-for="op in optionsmid"
                :key="op.value"
                :label="op.label"
                :value="op.value"
                 v-show="op.filters.includes(andItem.fieldObj && andItem.fieldObj.type)"
                >
              </el-option>
            </el-select>
            <input-type :filterModule="true" :operator="andItem.operator" v-if="!['empty', 'nempty', ''].includes(andItem.operator)" :propValue="andItem.value" :propData="andItem.fieldObj" @updatePropValue="updatePropValue($event, mindex, index, 'andConditions')"></input-type>
            <i class="V7_iconfont V7_iconV7tubiao-109 delete" @click="deleteItem(mindex, index, 'andConditions')"></i>
          </div>
          <div class="selectgroup">
            <el-button type="text" icon="el-icon-plus" @click="addItem(mindex, index, 'andConditions')">添加条件</el-button>
          </div>
        </div>
      </div>
      <div class="clearfix content-wrap">
        <p style="width:100%;font-size:12px;">满足以下任一条件</p>
        <div class="left">
          <span style="margin:auto">或</span>
        </div>
        <div class="right">
          <div class="selectgroup" v-for="orItem, index in group.orConditions" :key="index">
            <el-select filterable v-model="orItem.field" placeholder="请选择" class="filed-select" @change="changeFiled($event, mindex, index, 'orConditions')">
              <el-option
                v-for="orFileItem, index in filedConfig"
                :key="index"
                :label="orFileItem.alias || orFileItem.name"
                :value="orFileItem.field"
                >
              </el-option>
            </el-select>
            <el-select filterable v-model="orItem.operator" @change="changeOprator(mindex, index, 'orConditions')" placeholder="请选择" class="filed-select">
              <el-option
                v-for="op in optionsmid"
                :key="op.value"
                :label="op.label"
                :value="op.value"
                v-show="op.filters.includes(orItem.fieldObj && orItem.fieldObj.type)"
                >
              </el-option>
            </el-select>
            <input-type :filterModule="true" :operator="orItem.operator"  v-if="!['empty', 'nempty', ''].includes(orItem.operator)" :propValue="orItem.value" :propData="orItem.fieldObj" @updatePropValue="updatePropValue($event, mindex, index, 'orConditions')"></input-type>
            <i class="V7_iconfont V7_iconV7tubiao-109 delete" @click="deleteItem(mindex, index, 'orConditions')"></i>
          </div>
          <div class="selectgroup">
            <el-button type="text" icon="el-icon-plus" @click="addItem(mindex, index, 'orConditions')">添加条件</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
/**
 * 过滤器组件
 * 设置数据 setData
 * 获取数据 getData
 */
import { Component, Vue } from 'vue-property-decorator';
import InputType from '@/views/newCustomer/common/inputType.vue'
import { commonAction, deepClone } from '@/utils/common'
const defaultData = [
  {
    andConditions: [],
    orConditions: []
  }
]
@Component({
  name: 'FilterConfig',
  components: { InputType }
})
export default class FilterConfig extends Vue {
  private groups: any = []
  private $message: any
  private $store: any
  private $getCache: any
  private optionsmid = [
    {
      value: 'eq',
      label: '等于',
      filters: ['text', 'multi-text', 'dropdown', 'checkbox', 'radio', 'number', 'cascade', 'date', 'datetime', 'date-range', 'datetime-range', 'other']
    }, {
      value: 'neq',
      label: '不等于',
      filters: ['text', 'multi-text', 'dropdown', 'checkbox', 'radio', 'number', 'cascade', 'date', 'datetime', 'date-range', 'datetime-range', 'other']
    }, {
      value: 'in',
      label: '包含',
      filters: ['text', 'multi-text', 'dropdown', 'checkbox', 'radio', 'cascade', 'other']
    }, {
      value: 'nin',
      label: '不包含',
      filters: ['text', 'multi-text', 'dropdown', 'checkbox', 'radio', 'cascade', 'other']
    }, {
      value: 'empty',
      label: '为空',
      filters: ['text', 'multi-text', 'dropdown', 'checkbox', 'radio', 'number', 'cascade', 'date', 'datetime', 'date-range', 'datetime-range', 'attachment', 'other']
    }, {
      value: 'nempty',
      label: '不为空',
      filters: ['text', 'multi-text', 'dropdown', 'checkbox', 'radio', 'number', 'cascade', 'date', 'datetime', 'date-range', 'datetime-range', 'attachment', 'other']
    }, {
      value: 'gt',
      label: '大于',
      filters: ['number', 'date', 'datetime']
    }, {
      value: 'lt',
      label: '小于',
      filters: ['number', 'date', 'datetime']
    }, {
      value: 'gte',
      label: '大于等于',
      filters: ['number', 'date', 'datetime']
    }, {
      value: 'lte',
      label: '小于等于',
      filters: ['number', 'date', 'datetime']
    }, {
      value: 'between',
      label: '介于',
      filters: ['number', 'date', 'datetime', 'date-range', 'datetime-range']
    }
  ]

  private filedConfig = []

  get getCustomerAllLabels () {
    let labelList = this.$store.state.common.publicCache.customerAllLabels || []
    labelList = labelList.filter(v => v.enabled)
    return labelList.map(v => ({ value: v.name, key: v._id }))
  }

  get getUserList () {
    return this.$store.state.common.publicCache.userList.map(v => ({ value: `${v.agentName} 【${v.agentNumber}】`, key: v._id }))
  }

  get getRegionList () {
    return this.$store.state.common.publicCache.region.result || []
  }

  private updatePropValue (data, mindex, index, type) {
    if (data.type === 'number' && data.operator === 'between') {
      this.$set(this.groups[mindex][type][index], 'value', data.value)
      this.$set(this.groups[mindex][type][index], 'value2', data.value2)
    } else {
      this.$set(this.groups[mindex][type][index], 'value', data)
    }
  }

  // 添加条件
  private addItem (mindex, index, type) {
    if (this.groups[mindex][type].length >= 10) {
      this.$message.error('最多允许添加10个条件')
      return false
    }
    this.groups[mindex][type].push({
      fieldObj: {},
      operator: '',
      value: ''
    })
  }

  // 删除
  private deleteItem (mindex, index, type) {
    this.groups[mindex][type].splice(index, 1)
    if (this.groups[mindex][type].length === 0) {
      this.groups[mindex][type].splice(index, 1)
    }
  }

  // change 客户字段的时候，动态修改可选择的条件类型
  private changeFiled (filed, mindex, index, type) {
    this.$set(this.groups[mindex][type][index], 'operator', '')
    this.$set(this.groups[mindex][type][index], 'value', '')
    this.$set(this.groups[mindex][type][index], 'value2', '')
    let fieldObj = []
    fieldObj = this.filedConfig.filter((item: any) => {
      return item.field === filed
    })
    this.$set(this.groups[mindex][type][index], 'fieldObj', fieldObj[0] || {})
  }

  // change 条件的时候，后面的value值也要置空
  private changeOprator (mindex, index, type) {
    this.$set(this.groups[mindex][type][index], 'value', '')
    this.$set(this.groups[mindex][type][index], 'value2', '')
  }

  // 设置数据
  private async setData (data: any, type: string) {
    if (this.filedConfig.length <= 0) { // 字段配置，还没取过，要先取一下
      await this.handleCache()
    }
    if (type === 'add' || (data && data.length <= 0)) { // 没有筛选条件组，默认补上筛选条件
      this.groups = deepClone(defaultData)
    } else {
      const cloneData = deepClone(data)
      this.groups = this.handleData(cloneData)
    }
  }

  private handleData (data) { // 赋值之前，整理表单
    data.forEach(item => {
      Object.keys(item).forEach((conditionItem: any) => {
        if (item[conditionItem] && typeof item[conditionItem] === 'object') {
          item[conditionItem].forEach(andItem => {
            let fieldObj = []
            fieldObj = this.filedConfig.filter((fieldItem: any) => {
              return fieldItem.field === andItem.field
            })
            andItem.fieldObj = fieldObj[0] || {}
            const fileType = andItem.fieldObj.type
            if (['date', 'datetime', 'radio'].includes(fileType) && andItem.operator !== 'between') { // 条件是介于的，由子组件处理
              andItem.value = andItem.value[0] || ''
            }
          })
        }
      })
    })
    return data
  }

  // 获取数据
  public getData () {
    return deepClone(this.groups)
  }

  private async getFields () { // 获取客户字段配置
    const params = ({ url: '/server-crm/action/config/customer/field/list', method: 'POST', data: {} })
    const result = await commonAction(params)
    if (result.success && result.data) {
      const resultList = result.data.list || []
      resultList.forEach(item => {
        if (item.field === 'labels') { // 客户标签
          item.choices = this.getCustomerAllLabels || []
        } else if (['lastCallUser', 'lastChatUser', 'updateUser', 'createUser', 'firstOwner', 'owner'].includes(item.field)) { // 跟人有关的字段
          item.choices = this.getUserList || []
        } else if (item.field === 'region') { // 省市区
          item.options = {}
          item.options.children = this.getRegionList || []
        }
      })
      this.filedConfig = resultList
    }
  }

  private handleCache () { // 处理缓存
    return this.$getCache('/server-crm/action/customer/common/labels', ['customerAllLabels'], true, false, false, 'GET', false, 'data').then(() => { // 客户标签
      return this.$getCache('/base/action/general/cache/query', ['region'], false).then(res => {
        return this.getFields()
      })
    })
  }
}
</script>

<style lang="stylus" scoped>
.filterconfig
  .content-wrap
    display flex
    flex-wrap wrap
    .left
      flex 0 0 50px
      display flex
      margin 30px 0px
      border-right 1px solid $border-main
      font-size 12px
      color $fc-gray2
    .right
      flex 1
      .selectgroup
        width 100%
        display flex
        padding-left 30px
        margin 10px 0px
        position relative
        height 40px
        &::before
          position absolute
          content ''
          width 30px
          height 1px
          background $border-main
          top 50%
          left 0px
        .filed-select
          margin-right 16px
        .delete
          flex 0 0 20px
          margin-left 16px
          &:hover
            color $c-danger
            cursor pointer
</style>
